package com.fhzn.auth.entity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fhzn.commons.toolkit.entity.HttpResponse;
import org.springframework.http.*;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

/**
 * @author fhzn
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class WebResponse<T> extends HttpResponse<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    @JsonCreator
    public WebResponse(@JsonProperty(required = true, value = "code") int code,
                       @JsonProperty(value = "message") String message,
                       @JsonProperty(value = "data") T data) {
        super(code, message, data);
    }

    public static WebResponse<Void> success() {
        return new WebResponse<>(SUCCESS, OK, null);
    }

    public static <T> WebResponse<T> success(T data) {
        return new WebResponse<>(SUCCESS, OK, data);
    }

    public static <T> WebResponse<T> error(String error) {
        return new WebResponse<>(ERROR, error, null);
    }

    public static <T> WebResponse<T> error(int code, String error) {
        return new WebResponse<>(code, error, null);
    }

    public static <T> WebResponse<T> error(HttpStatus httpStatus, String error) {
        return new WebResponse<>(-1, error, null);
    }

    public static ResponseEntity<DeleteAfterReadeFileSystemResource> ofFileBytes(String name, Path file) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(name, StandardCharsets.UTF_8).build().toString());
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return new ResponseEntity<>(new DeleteAfterReadeFileSystemResource(file), headers, HttpStatus.OK);
    }

    public String toString() {
        return super.toString();
    }
}
